package com.dylan.springcloud.zuul.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * Created by Dylan on 2018/10/19.
 */
@Component
public class PostFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("这是PostFilter！");
        //从RequestContext获取上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.getResponse().setContentType("application/json;charset=UTF-8");
        String responseBody = ctx.getResponseBody();
        System.out.println("请求响应内容：" + responseBody);
        if (responseBody != null) {
            // 设置返回状态码
            ctx.setResponseStatusCode(500);
            // 替换响应报文
            ctx.setResponseBody("{\"status\":500,\"message\":\"计算失败！\"}");
        }
        return null;
    }
}
